//电影管理

var express = require('express');
var router = express.Router();
var sqlQuery = require('../../../module/sql');
var jiami = require('../../../module/jiami')
var fs = require('fs')
//引入上传模块
var multer = require('multer');
//上传的配置
var upload = multer({dest:"./public/upload"});

/* GET users listing. */
router.get('/', async(req, res, next)=>{
  let type = await getType()
    let options = {type};
  res.render('admin/film/filmadd',options)
});

//获取用户角色
async function getType(){
    let sqlStr = 'select * from type'
    let result = await sqlQuery(sqlStr);
    //结果返回
    return Array.from(result);
  }


  router.post('/poster',upload.single('poster'), async(req, res, next)=> {
        let filmid = req.body.filmid
        let result = rename(req)
        res.json(result)
      })
      //改名函数
      function rename(req) {
        //重命名操作
        let oldPath = req.file.destination+"/"+req.file.filename;
        let newPath = req.file.destination+"/"+req.file.filename+req.file.originalname;
        fs.rename(oldPath,newPath,()=>{
          //console.log("重命名成功")
        })
        return {
          state:'ok',
          imgUrl:"/upload/"+req.file.filename+req.file.originalname
        }
       }


router.post('/', async(req, res)=>{
  let username = req.session.username
  let sqlStr2 = 'select id from user where username = ?'
  let result2 = await sqlQuery(sqlStr2,[username]);
  //结果返回
  let uid = result2[0].id
  // console.log("-------------------------uid:",uid)
  let filmName = req.body.filmName
  let sqlStr1 = 'select * from film where filmName = ?'
  let result1 = await sqlQuery(sqlStr1,filmName)
  if(result1.length == 0){
    let Typeid = req.body.typeid
    let year = req.body.year
    let director = req.body.director
    let region = req.body.region
    let brief = req.body.brief
    let movieUrl = req.body.movieUrl
    let poster = req.body.img_h
    let state = req.body.state
    if(state == 'on'){
        state = 1
    }else{
        state = 0
    }
    let sqlStr = "insert into film (filmName,Typeid,year,director,region,brief,state,movieUrl,userid,poster) values(?,?,?,?,?,?,?,?,?,?)"
    let arr = [filmName,Typeid,year,director,region,brief,state,movieUrl,uid,poster]
    await sqlQuery(sqlStr,arr)
    res.json({
        state:"ok",
        content:"发布电影成功"
      })
  }else{
    res.json({
      state:"ok",
      content:"此电影已发布！"
    })
  }

})


module.exports = router;
